package com.auto.api.framework.strategy;

import com.auto.api.common.exception.BusinessException;
import com.google.common.collect.Maps;
import java.util.Collection;
import java.util.Map;
import javax.annotation.PostConstruct;

/**
 * @param <S> 策略
 * @param <C> 条件 类说明 策略条件容器实现类
 * @author liangshf
 * @version 创建时间：2019年7月26日
 */
public abstract class AbstractStrategyContainer<C, S extends IStrategy<C>> implements IStrategyContainer<C, S> {

    private Map<String, S> container;

    /**
     * 通过传入的策略条件转化 容器存储key
     */
    public abstract String getContainerKey(C c);

    /**
     * 获取默认容器
     */
    public abstract Map<String, S> getStrategys();

    @PostConstruct
    public void setContainer() {
        this.container = getStrategys();
    }

    @Override
    public S getStrategy(C c) {
        if (container == null) {
            throw new BusinessException("容器未初始化");
        }
        return container.get(getContainerKey(c));
    }

    @Override
    public void registerStrategy(S s) {
        if (container == null) {
            container = Maps.newHashMap();
        }
        if (container.get(getContainerKey(s.getCondition())) != null) {
            throw new BusinessException(s.getCondition() + "-" + s + "重复注册!");
        }
        container.put(getContainerKey(s.getCondition()), s);
    }

    @Override
    public void registerStrategys(Collection<S> collection) {
        for (final S s : collection) {
            registerStrategy(s);
        }

    }

}
